package org.lql.algo.codecrush.hot100.matrix;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: liangqinglong
 * @date: 2025-10-11 17:45
 * @description: 54. 螺旋矩阵 <a href="https://leetcode.cn/problems/spiral-matrix/description/?envType=study-plan-v2&envId=top-100-liked">...</a>
 **/
public class SpiralOrder {

	public List<Integer> spiralOrder(int[][] matrix) {
		List<Integer> result = new ArrayList<>();
		if (matrix == null || matrix.length == 0) {
			return result;
		}
		int row = matrix.length;
		int col = matrix[0].length;
		int left = 0;
		int right = col - 1;
		int top = 0;
		int bottom = row - 1;
		while (left <= right && top <= bottom) {
			// 上边界
			for (int i = left; i <= right; i++) {
				result.add(matrix[top][i]);
			}
			top++;
			// 右边界
			for (int i = top; i <= bottom; i++) {
				result.add(matrix[i][right]);
			}
			right--;
			// 下边界
			if (top <= bottom) {
				for (int i = right; i >= left; i--) {
					result.add(matrix[bottom][i]);
				}
				bottom--;
			}
			// 左边界
			if (left <= right) {
				for (int i = bottom; i >= top; i--) {
					result.add(matrix[i][left]);
				}
				left++;
			}
		}
		return result;
	}

	public static void main(String[] args) {
		int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
		List<Integer> result = new SpiralOrder().spiralOrder(matrix);
		System.out.println(result);
	}
}
